package com.ytjj.quartz.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.constants.DateUtils;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.DateTimeUtil;
import com.ytjj.common.utils.HttpClientUtil;
import com.ytjj.common.utils.feishu.FeiShuUtil;
import com.ytjj.qmyx.mall.mapper.*;
import com.ytjj.qmyx.mall.model.OrdersInfo;
import com.ytjj.qmyx.mall.model.*;
import com.ytjj.qmyx.users.client.AdminClient;
import com.ytjj.quartz.config.SupplyApiConfig;
import com.ytjj.quartz.dao.ReturnGoodsDao;
import com.ytjj.quartz.enums.OrderStatusEnums;
import com.ytjj.quartz.model.YxReturnGoods;
import com.ytjj.quartz.model.*;
import com.ytjj.quartz.model.dto.ReturnGoodsDto;
import com.ytjj.quartz.utils.TimingDate;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.map.LinkedMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 * 
 * @Version: 1.0
 */
@Service
@Slf4j
@AllArgsConstructor
public class ReturnGoodsService {

    @Resource
    private ReturnGoodsDao returnGoodsDao;
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private OrdersInfoMapper ordersInfoMapper;
    @Resource
    private SupplyApiConfig supplyApiConfig;
    @Resource
    private ProductMapper productMapper;
    @Resource
    private AdminClient adminClient;
    @Resource
    private ReturnGoodsOtherService returnGoodsOtherService;
    @Resource
    private OrdersService ordersService;

    private TimingDate timingDate;


    public void verifyLogistics() {
        //获取所有寄回中的商品物流信息
        List<ReturnGoodsResponse> responseList = returnGoodsDao.selectList();
        if (!CollectionUtils.isEmpty(responseList)) {
            List<String> serviceNoList = responseList.stream().map(ReturnGoodsResponse::getServiceNo).collect(Collectors.toList());
            List<ReturnGoodsQueryResponse> returnGoodsQueryResponses = queryReturnGoods(serviceNoList);
            for (ReturnGoodsResponse returnGoods : responseList) {
                List<ReturnGoodsQueryResponse> collect = returnGoodsQueryResponses.stream().filter(item -> item.getServiceNo().equals(returnGoods.getServiceNo())).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(collect)) {
                    return;
                }
                ReturnGoodsQueryResponse response = collect.get(0);
                Boolean flag = false;
                if (!response.getStatus().equals(returnGoods.getStatus())) {
                    returnGoods.setStatus(response.getStatus());
                    flag = true;
                }
                if (!response.getGetExpressTime().equals(returnGoods.getGetExpressTime())) {
                    returnGoods.setGetExpressTime(response.getGetExpressTime());
                    flag = true;
                }
                if (flag) {
                    returnGoodsDao.updateStatus(returnGoods.getId());
                }
            }
        }
    }

    public void verifyBankerRece() {
        // 获取所有已签收快递，但供应商没有审核的数据
        List<ReturnBankerReceResponse> pageList = returnGoodsDao.selectReceList();
        if (!CollectionUtils.isEmpty(pageList)) {
            for (ReturnBankerReceResponse rece : pageList) {
                if (null == rece.getGetExpressTime()) {
                    continue;
                }
                // 计算两个时间之间的差
                long different = System.currentTimeMillis() - rece.getGetExpressTime().getTime();

                long secondsTime = 1000;
                long minutesTime = secondsTime * 60;
                long hoursTime = minutesTime * 60;

                long getHoursDiff = different / hoursTime;

                // 退货商品的快递识别为已签收后24h,供应商还未进行任何审核操作
                // 默认将供应商审核状态改为审核通过
                log.debug("===timingDate.getAuditDate={},{}", timingDate.getAuditDate(), rece.getId());
                if (getHoursDiff > 24) {
                    returnGoodsDao.updateBankerStatus(rece.getId());
                    try {
                        YxReturnGoods yxReturnGoods = new YxReturnGoods();
                        yxReturnGoods.setServiceNo(rece.getServiceNo());
                        yxReturnGoods.setBankerStatus(2);
                        yxReturnGoods.setBankerApplyTime(new Date());
                        yxReturnGoods.setStatus(4);
                        updateReturnGoods(yxReturnGoods);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }


    /**
     * 售后失败回到原状态
     * @param orderInfoId
     * @param orderInfoStatus
     * @param serviceNo
     * @return Integer
     */
    public Integer rollbackOrderStatus(Integer orderInfoId,String orderInfoStatus,String serviceNo,String ServiceDesc){
        Integer resultMark = 0;
        if (!org.springframework.util.StringUtils.isEmpty(orderInfoStatus)) {
            OrdersInfo ordersInfo = new OrdersInfo();
            ordersInfo.setId(orderInfoId);
            ordersInfo.setOrderinfoStatus(orderInfoStatus);
            ordersInfoMapper.updateByPrimaryKeySelective(ordersInfo);
            //查询该子订单所属的主订单有多少个子订单
            OrdersInfo orderInfoEntity = ordersInfoMapper.selectByPrimaryKey(orderInfoId);
            OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
            ordersInfoExample.createCriteria().andOrderIdEqualTo(orderInfoEntity.getOrderId());
            List<OrdersInfo> ordersInfos = ordersInfoMapper.selectByExample(ordersInfoExample);
            if (ordersInfos.size() > 0 && ordersInfos.size() < 2) {
                Orders orders = new Orders();
                orders.setOrderStatus(orderInfoStatus);
                orders.setId(orderInfoEntity.getOrderId());
                ordersMapper.updateByPrimaryKeySelective(orders);
            }
            //TODO 如果有多个子订单的情况下,主订单有没有修改,要不要把主订单恢复
            //修改供应链订单状态
            List<String> childOrderNoList = new ArrayList<>();
            childOrderNoList.add(orderInfoEntity.getChildOrderNo());
            UpdateOrderInfoRequest updateOrderInfoRequest = new UpdateOrderInfoRequest();
            updateOrderInfoRequest.setChildOrderNoList(childOrderNoList);
            updateOrderInfoRequest.setOrderStatus(Integer.valueOf(orderInfoStatus));
            updateOrderInfoRequest.setServiceNo(serviceNo);
            updateOrderInfoRequest.setServiceDesc(ServiceDesc);
            String json = JSON.toJSONString(updateOrderInfoRequest);
            String result = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/updateOrderInfo", json, supplyApiConfig.getHeadsMap());
            CommonResult commonResult = JSONObject.parseObject(result, CommonResult.class);
            if (null == commonResult || 200 != commonResult.getCode()) {
                log.error("恢复供应链订单状态出错====={}",commonResult.getMessage());
                resultMark = 0;
            }else {
                resultMark = 1;
            }
        }
        return resultMark;
    }

    public void verifyBankerStatus() {
        //查询正在售后的订单
        List<ReturnGoods> list = returnGoodsDao.selectByAfterType();
        list.stream().forEach(item->{
            returnGoodsOtherService.updateBankerStatusByAfterType(item);
        });
    }

    public void verifyReturnRegister() {
        List<ReturnGoods> returnGoodsList = returnGoodsDao.selectByIsRefund();
        //todo 目前订单购买的商品数量只有1
        final Integer sum = 1;
        returnGoodsList.stream().forEach(returnGoods -> {
            OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(returnGoods.getOrdersInfoId());
            // 加库存 减销量
            Product product = productMapper.selectByPrimaryKey(ordersInfo.getProductId());
            //加库存
            try {
                subAndAddStock(ordersInfo.getChildOrderNo(), sum, product.getIsZeroProduct(), "add");
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    public void checkSupplyChainReturnGoods() {
        List<ReturnGoods> returnGoodsList = returnGoodsDao.select();
        if (CollectionUtils.isEmpty(returnGoodsList)) {
            return;
        }
        List<String> serviceNoList = returnGoodsList.stream().map(ReturnGoods::getServiceNo).collect(Collectors.toList());
        System.out.println(serviceNoList);
        List<ReturnGoodsQueryResponse> returnGoodsQueryResponses = queryReturnGoods(serviceNoList);
        log.info("==============查询供应链返回信息========returnGoodsQueryResponses:==========={}", returnGoodsQueryResponses);
        for (ReturnGoods returnGoods : returnGoodsList) {
            List<ReturnGoodsQueryResponse> collect = returnGoodsQueryResponses.stream().filter(item -> item.getServiceNo().equals(returnGoods.getServiceNo())).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                ReturnGoodsQueryResponse response = collect.get(0);
                Boolean flag = false;
                if (null != response.getBankerApplyTime() && response.getBankerApplyTime() != returnGoods.getBankerApplyTime()) {
                    returnGoods.setBankerApplyTime(response.getBankerApplyTime());
                    flag = true;
                }
                if (org.apache.commons.lang3.StringUtils.isNotBlank(response.getBankerRemarks()) && response.getBankerRemarks() != returnGoods.getBankerRemarks()) {
                    returnGoods.setBankerRemarks(response.getBankerRemarks());
                    flag = true;
                }
                if (null != response.getBankerStatus() && !response.getBankerStatus().equals(returnGoods.getBankerStatus())) {
                    returnGoods.setBankerStatus(response.getBankerStatus());
                    flag = true;
                }
                if (null != response.getStatus() && !response.getStatus().equals(returnGoods.getStatus())) {
                    returnGoods.setStatus(response.getStatus());
                    //如果供应商审核同意并且子订单是已退款  则修改状态为9
                    if (returnGoods.getBankerStatus()==2 && response.getStatus()==4){
                        Integer isRefund = ordersInfoMapper.selectIsRefund(returnGoods.getOrdersInfoId());
                        if (isRefund!=null && isRefund==1){
                            returnGoods.setStatus(9);
                        }
                    }
                    if (!StringUtils.isEmpty(response.getServiceBeizhu()) && !response.getServiceBeizhu().equals(returnGoods.getServiceBeizhu())) {
                        returnGoods.setServiceBeizhu(response.getServiceBeizhu());
                    }
                    flag = true;
                }
                if (null != response.getGetExpressTime() && response.getGetExpressTime() != returnGoods.getGetExpressTime()) {
                    returnGoods.setGetExpressTime(response.getGetExpressTime());
                    flag = true;
                }
                if (flag) {
                    returnGoodsMapper.updateByPrimaryKeySelective(returnGoods);
                }
            }
        }


    }

    /**
     * 查询供应链的售后订单信息
     */
    public List<ReturnGoodsQueryResponse> queryReturnGoods(List<String> serviceNoList) {
        ReturnGoodsQueryRequest returnGoodsQueryRequest = new ReturnGoodsQueryRequest();
        returnGoodsQueryRequest.setServiceNo(serviceNoList);
        returnGoodsQueryRequest.setShopId(supplyApiConfig.getShopId());
        String json = JSON.toJSONString(returnGoodsQueryRequest);
        String resultJson = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/queryReturnGoods", json, supplyApiConfig.getHeadsMap());
        log.debug("===========查询供应商售后信息======返回======={}", resultJson);
        if (StringUtils.isEmpty(resultJson)) {
            return new ArrayList<>();
        }
        List<ReturnGoodsQueryResponse> orderQueryResponses = JSONObject.parseArray(resultJson, ReturnGoodsQueryResponse.class);
        return orderQueryResponses;
    }

    public String updateReturnGoods(YxReturnGoods yxReturnGoods) {
        yxReturnGoods.setShopId(supplyApiConfig.getShopId());
        String json = com.gexin.fastjson.JSON.toJSONString(yxReturnGoods);
        String s = HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/returnGoods/updateReturnGoods", json, supplyApiConfig.getHeadsMap());
        return s;
    }

    /**
     * 扣减或退还库存
     *
     * @param num  商品数量
     * @param type sub-扣减 add-退还
     * @return
     */
    public void subAndAddStock(String orderNo, Integer num, Integer isZeroProduct, String type) {
        Map<String, String> map = new LinkedMap();
        map.put("orderNo", orderNo);
        map.put("num", String.valueOf(num));
        map.put("isZeroProduct", String.valueOf(isZeroProduct));
        map.put("type", type);
        HttpClientUtil.doGet(supplyApiConfig.getUrl() + "/stock/subAndAddStock", map, supplyApiConfig.getHeadsMap());
    }

    /**
     * 已修复正在进行售后的订单的状态异常的订单
     * @param
     * @return void
     */
    public void verifyReturnGoodsOrders(String childOrderNos) {
        List<String> list = new ArrayList<>();
        if(!StringUtils.isEmpty(childOrderNos)){
            list = Arrays.asList(childOrderNos.split(","));
        }
        List<ReturnGoodsDto> returnGoodsDtos = returnGoodsDao.selectFailStatus(list);
        //需要回到原状态的订单
        List<ReturnGoodsDto> collect = returnGoodsDtos.stream().filter(e -> {
            String statusStr = e.getStatusStr();
            List<String> strings = Arrays.asList(statusStr.split(","));
            //过滤状态正常的订单
            if (strings.contains("1") || strings.contains("2") || strings.contains("3") || strings.contains("4") || strings.contains("8")) {
                return false;
            } else {
                return true;
            }
        }).collect(Collectors.toList());
        //状态需要修复的订单
        collect.stream().forEach(e->{
            //查询当前子订单状态
            OrdersInfo ordersInfo = ordersInfoMapper.selectByPrimaryKey(e.getOrderInfoId());
            //查询当前主订单状态
            Orders orders = ordersMapper.selectByPrimaryKey(ordersInfo.getOrderId());
            if (OrderStatusEnums.REFUND.getValue().equals(ordersInfo.getOrderinfoStatus()) || OrderStatusEnums.REFUND.getValue().equals(orders.getOrderStatus())) {
                String orangeStatus = "";
                try {
                    List<String> returnStatus = Arrays.asList(e.getStatusStr().split(","));
                    //需要关闭
                    if(returnStatus.contains("9")){
                        //订单状态设置关闭
                        orangeStatus = OrderStatusEnums.CLOSED.getValue();
                    }else {//需要回到原状态
                        CommonResult result = adminClient.getRedisString("return:good:orderInfoStatus" + ordersInfo.getId());
                        if (result.getCode() != 200 || null == result.getData()
                                || (null != result.getData() && OrderStatusEnums.REFUND.getValue().equals(result.getData().toString()))) {
                            //防止Redis没有原状态或者还是售后状态,需要根据实际情况设置值
                            if (!com.alibaba.excel.util.StringUtils.isEmpty(ordersInfo.getExpressNo()) && !com.alibaba.excel.util.StringUtils.isEmpty(ordersInfo.getExpressCompanyNo())) {
                                orangeStatus = OrderStatusEnums.SHIPPED.getValue();
                            } else {
                                orangeStatus = OrderStatusEnums.UNSHIPPED.getValue();
                            }
                        }else {
                            orangeStatus = result.getData().toString();
                        }
                    }
                    //更新主订单
                    Orders order = new Orders();
                    order.setOrderStatus(orangeStatus);
                    OrdersExample ordersExample = new OrdersExample();
                    ordersExample.createCriteria().andIdEqualTo(orders.getId()).andOrderStatusEqualTo(orders.getOrderStatus());
                    ordersMapper.updateByExampleSelective(order, ordersExample);
                    //更新子订单
                    OrdersInfo ordersInfo1 = new OrdersInfo();
                    ordersInfo1.setOrderinfoStatus(orangeStatus);
                    OrdersInfoExample ordersInfoExample = new OrdersInfoExample();
                    ordersInfoExample.createCriteria().andIdEqualTo(ordersInfo.getId()).andOrderinfoStatusEqualTo(ordersInfo.getOrderinfoStatus());
                    ordersInfoMapper.updateByExampleSelective(ordersInfo1,ordersInfoExample);
                    //更新供应链订单状态
                    UpdateOrderRequest updateOrderStatusRequest = new UpdateOrderRequest();
                    updateOrderStatusRequest.setChildOrderNo(ordersInfo.getChildOrderNo());
                    updateOrderStatusRequest.setShopId(supplyApiConfig.getShopId());
                    updateOrderStatusRequest.setOrderStatus(Integer.valueOf(orangeStatus));
                    String json = JSON.toJSONString(updateOrderStatusRequest);
                    HttpClientUtil.doPostJson(supplyApiConfig.getUrl() + "/order/updateOrderStatus", json, supplyApiConfig.getHeadsMap());
                    log.info(String.format("===========已修复售后订单状态：子订单号：%s,原状态：主订单%s,子订单%s。修复后状态%s",ordersInfo.getChildOrderNo(),orders.getOrderStatus(),ordersInfo.getOrderinfoStatus(),orangeStatus));
                } catch (Exception ex) {
                    log.error("获取订单原状态出错！",ex);
                }
            }
        });
    }

    public void verifyReturnGoodsAudit() {
        returnGoodsDao.updateServiceStatus2ByStatus();
        returnGoodsDao.updateServiceStatus3ByStatus();
    }

    public void automaticRefund(int day) {
        List<ReturnRegister> returnRegisterList = returnGoodsDao.queryReturnGoodsByDay(day);
        if (!CollectionUtils.isEmpty(returnRegisterList)) {
            List<Integer> orderInfoIdList = returnRegisterList.stream().filter(item -> item.getOrderInfoId() != null).map(ReturnRegister::getOrderInfoId).collect(Collectors.toList());
            List<Integer> lockOrderInfoIdList = returnGoodsDao.getLockOrderInfo(orderInfoIdList);
            if (!CollectionUtils.isEmpty(lockOrderInfoIdList)) {
                returnRegisterList = returnRegisterList.stream().filter(item -> !lockOrderInfoIdList.contains(item.getOrderInfoId())).collect(Collectors.toList());
            }
            List<String> orderNoList = returnRegisterList.stream().filter(item -> null != item.getOrderNo()).map(ReturnRegister::getOrderNo).collect(Collectors.toList());
            log.info("系统自动退款订单号为:{}",JSONObject.toJSONString(orderNoList));
            for (ReturnRegister returnRegister : returnRegisterList) {
                try{
                    adminClient.refundOperaRpc(returnRegister.getId(), "系统自动退款");
                }catch (Exception e) {
                    log.error("系统自动退款失败,订单号为:{},错误原因为:{}",returnRegister.getOrderNo(),e.getMessage());
                    FeiShuUtil.sendMsg(String.format("系统自动退款出错,%s,出错订单号为:%s",e.getMessage(),returnRegister.getOrderNo()));
                }

            }
        }
    }

    public void orderReturnAuto(){
        List<ReturnRegister> returnRegisterList =returnGoodsDao.getOrderReturnAuto();
        if (!CollectionUtils.isEmpty(returnRegisterList)) {
            List<Integer> orderInfoIdList = returnRegisterList.stream().filter(item -> item.getOrderInfoId() != null).map(ReturnRegister::getOrderInfoId).collect(Collectors.toList());
            List<Integer> lockOrderInfoIdList = returnGoodsDao.getLockOrderInfo(orderInfoIdList);
            if (!CollectionUtils.isEmpty(lockOrderInfoIdList)) {
                returnRegisterList = returnRegisterList.stream().filter(item -> !lockOrderInfoIdList.contains(item.getOrderInfoId())).collect(Collectors.toList());
            }
            List<String> orderNoList = returnRegisterList.stream().filter(item -> null != item.getOrderNo()).map(ReturnRegister::getOrderNo).collect(Collectors.toList());
            log.info("客服标记自动退款订单号为:{}",JSONObject.toJSONString(orderNoList));
            for (ReturnRegister returnRegister : returnRegisterList) {
                try{
                    String result = adminClient.refundOperaRpc(returnRegister.getId(), "系统自动退款");
                    if ("200".equals(result)){
                        returnGoodsDao.updateOrderReturnAutoState(returnRegister.getOrderInfoId());
                    }
                }catch (Exception e) {
                    log.error("客服标记自动退款,订单号为:{},错误原因为:{}",returnRegister.getOrderNo(),e.getMessage());
                    FeiShuUtil.sendMsg(String.format("客服标记自动退款出错,%s,出错订单号为:%s",e.getMessage(),returnRegister.getOrderNo()));
                }
            }
        }

    }

    public void syncReturnRegisterByMark(){
        adminClient.syncReturnRegisterByMark();
    }
}
